package game;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

import java.awt.Cursor;

/*整个窗口是边界布局  北边和中间是两块
北边 
    两个按钮  开始游戏   结束游戏
     中间 JPanel 网格布局
     9个按钮  按钮上是图片
*/
public class MouseJPanel extends JPanel implements ActionListener{
	private int screenW = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
private int screenH = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();

//  2北部 中部  Jpanel
private JPanel northJpanel,centerJpanel;
// 北边jpanel的组件
//  1下拉框 JCombobox
private JComboBox<String> levelCombox;
//  5个标签  JLabel
private JLabel nameLabel,timeKeyLable,timeValueLabel,
scoreKeyLabel,scoreValueLabel;
//  1个按钮 JButton
private JButton startBtn;
// 南边jpanel的组件
private JButton[] mouseBtns;
private Timer mouseTimer;//时间倒计时
private Timer countTimer;
private int lastIndex; //上一次地鼠索引
private boolean isHit;//地鼠是否打过  默认是false
private int timeDelay = 650; //初始化游戏难度
//倒计时时间统一控制
private String timeValue = "10";
private User user;
java.applet.AudioClip bgm;
//定義音樂   背景音樂
private java.applet.AudioClip hm;
// 设置JFrame的样式
public MouseJPanel(User user) {
	this.setLayout(new BorderLayout());
     this.user =user;
     // 初始化组件
     initComponet();
	// 标题
	//this.setTitle("打地鼠");
	// 大小
//	this.setSize(400,500);
	// 位置
	//this.setLocation((screenW-this.getWidth())/2, (screenH-this.getHeight())/2);
	// 是否可扩大
	//this.setResizable(false);
	// 关闭窗口
	//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	// 是否可视化
	//this.setVisible(true);
}
// 初始化组件方法
private void initComponet() {
	//音樂
	URL bgmUrl = MouseJPanel.class.getClassLoader().getResource("images/secret.wav");
	bgm = JApplet.newAudioClip(bgmUrl);
	
	URL hmUrl = MouseJPanel.class.getClassLoader().getResource("images/jida.WMA");
	hm = JApplet.newAudioClip(hmUrl);
	
	// 北边初始化 默认流式布局
	northJpanel = new JPanel();
	// 选择框
	levelCombox = new JComboBox<String>(new String[] {"Simple","Common","Difficult"});
	// tom 倒计时 10 分数 0 
	nameLabel = new JLabel(user.getName());
	timeKeyLable = new JLabel("倒计时");
	timeValueLabel = new JLabel(timeValue);
	scoreKeyLabel = new JLabel("分数");
	scoreValueLabel = new JLabel("0");
	startBtn = new JButton("开始游戏");
	northJpanel.add(levelCombox);
	northJpanel.add(nameLabel);
	northJpanel.add(timeKeyLable);
	northJpanel.add(timeValueLabel);
	northJpanel.add(scoreKeyLabel);
	northJpanel.add(scoreValueLabel);
	northJpanel.add(startBtn);
	// 中间初始化
	centerJpanel = new JPanel();
	// 中间设置网格布局
	centerJpanel.setLayout(new GridLayout(3, 3));
	centerJpanel.setCursor(getCursor("src/images/hammerUp.png"));
	// 初始化9个地鼠按钮
	mouseBtns = new JButton[9];
	for(int i = 0 ; i<mouseBtns.length;i++) {
		// src/main/java/..  src/
		// 每个元素 都是一个按钮
		mouseBtns[i] = new JButton(new ImageIcon("D:\\QQDownload\\DownMouse.png"));
		centerJpanel.add(mouseBtns[i]);
		//给每个地鼠绑定监听器
		mouseBtns[i].addActionListener(this);
		mouseBtns[i].addMouseListener(new MyHammerListener());
	}
	
	// 1.开始游戏 事件 只有一个监听
	startBtn.addActionListener(this);
	mouseTimer = new Timer(timeDelay,this);
	countTimer = new Timer(1000,this);
	//3.难度选择
	levelCombox.addActionListener(this);
	this.add(northJpanel,BorderLayout.NORTH);
	this.add(centerJpanel); // 默认中间
}

public void actionPerformed(ActionEvent e) {
	Object source = e.getSource();
	



	//如果是开始按钮
	if(source == startBtn) {
		//如果是定时器
		//开启定时器
		mouseTimer.start();
		countTimer.start();
		bgm.loop();
		//按钮不能用
		startBtn.setEnabled(false);
		levelCombox.setEnabled(false);
	}else if(source == mouseTimer) {
		
		mouseBtns[lastIndex].setIcon(new ImageIcon("src/images/DownMouse.png"));
		//如果是定时器
		//需要实现随机出现地鼠的逻辑
		//1.随机产生索引
		int currentIndex =(int) (Math.random()*mouseBtns.length); //[0,)
		isHit = false;
		if(lastIndex == currentIndex) {
			currentIndex++;
			//解决两次索引相同的情况
			if(currentIndex == mouseBtns.length) {
				currentIndex = currentIndex-2;
				//控制数组越界
			}
		}
		//2.通过索引找到地鼠按钮
		mouseBtns[currentIndex].setIcon(new ImageIcon("src/images/UpMouse.png"));
		lastIndex = currentIndex;
		//3.换地鼠按钮的图片
		//4.顺便实现倒计时
		//5.游戏结束 保存文件记录
	
	}else if (source==countTimer) {
		int time = Integer.parseInt(timeValueLabel.getText());
		time--;
		timeValueLabel.setText(time+"");
		if(time==0) {
			mouseTimer.stop();
			countTimer.stop();
			//int finalScore = Integer.parseInt(scoreValueLabel.getText());
			JOptionPane.showMessageDialog(this, "Game Fucking Over ！"+"Score："+scoreValueLabel.getText());
			saveRecord();
			scoreValueLabel.setText(0+"");
			//此时的成员变量在timeValue 已经定义为10
			timeValueLabel.setText(timeValue);
			mouseBtns[lastIndex].setIcon(new ImageIcon("src/images/DownMouse.png"));
			startBtn.setEnabled(true);
			levelCombox.setEnabled(true);
		     isHit = true;
	}
	}else if(mouseBtns[lastIndex] == source) {
	//如果事件源是地鼠按钮
       // 刚好点击的是随机出现的地鼠 记分	
		if(!isHit) {
			hm.play();
			int score = Integer.parseInt(scoreValueLabel.getText());
			score +=10;
              scoreValueLabel.setText(String.valueOf(score));				
		
		isHit = true;
		}
		//scoreValueLabel.setText(score+"");

	// 数据源是开始游戏
	//如果是开始按钮   开启定时器
	// 如果是定时器
				//随机产生数组下标,将对应的按钮的图片换了
	// 数据源是地鼠按钮
	
	// 数据源是定时器
	
} else if(source== levelCombox) {
	//事件源是下拉框
	   // 获取下拉框字符串  修改定时器时间
        levelCombox = (JComboBox<String>) source;
        String selectedItem = (String) levelCombox.getSelectedItem();
        if("Simple".equals(selectedItem )) {
        	//Simple  1000
        	timeDelay = 650;
        }else if("Common".equals(selectedItem )) {
        	//Common  500
        	timeDelay = 400;
        }else if("Difficult".equals(selectedItem )) {
        	//Difficult
        	timeDelay = 150;
        }
//构造器已经初始化了  
        mouseTimer.setDelay(timeDelay);
        user.setLevel(selectedItem);
}
}
     class MyHammerListener extends MouseAdapter{
		@Override
		public void mousePressed(MouseEvent e) {
			//給當前按鈕  換光標
			JButton b = (JButton) e.getSource();
			//設置光標
			Cursor cursor = getCursor("src/images/hammerDown.png");
			b.setCursor(cursor);
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// 给当前按钮 换光标
						JButton b = (JButton) e.getSource();
						// 设置光标
						Cursor cursor = getCursor("src/images/hammerUp.png");
						b.setCursor(cursor);
					}
		
    }
     public Cursor getCursor(String imageUrl) {
    	 Image image = new ImageIcon(imageUrl).getImage();
    	 return  Toolkit
    			 .getDefaultToolkit()
    			 .createCustomCursor(image, new Point(), null);
    	 
     }
private void saveRecord() {
	//将user写到文件中
	user.setScore(Integer.parseInt(scoreValueLabel.getText()));
	user.setLevel((String)levelCombox.getSelectedItem());
	
	//封装工具类  RecordUtil.writeRecord
	RecordUtil.writeRecord(user);
//System.out.println(user);
}


}

